#!/usr/bin/python

import csv
import numpy as np
import matplotlib.pyplot as mplt
from numpy import inf
from scipy import fft

class plotcsv:
    def __init__(self, fname, firstrow=6, lastrow=inf, delimiter=",", xcol=0, ycol=1):
        self.mplt = mplt
        self.fname = fname
        reader = csv.reader(open(fname), delimiter=delimiter)

        self.x, self.y = [],[]
        for counter, row in enumerate(reader):
            if counter<firstrow-1 or counter>=lastrow:
                continue
            else:
                row = ' '.join(row).split()
                self.x.append(float(row[xcol]))
                self.y.append(float(row[ycol]))

        self.x = np.array(self.x)
        self.y = np.array(self.y)

        self.samprate = 1 / (self.x[1]-self.x[0])
        self.freq = np.arange(0,np.ceil(len(self.x)/2.0)) * self.samprate / np.ceil(len(self.x)/2.0)
        self.freq = np.concatenate((-1*self.freq[-1::-1], self.freq[1:]))
        self.xfft = fft(self.y)
        self.xfft = np.concatenate((self.xfft[np.ceil(len(self.xfft)/2.0):], self.xfft[:np.ceil(len(self.xfft)/2.0)]))

    def plot(self, formatstr='x'):
        self.fig  = mplt.figure()
        self.ax   = self.fig.add_subplot(111)
        self.line = mplt.plot(self.x, self.y, formatstr)
        self.t    = self.ax.set_title(self.fname)

    def logplot(self, formatstr='x'):
        self.fig  = mplt.figure()
        self.ax   = self.fig.add_subplot(111)
        self.line = mplt.semilogy(self.x, self.y, formatstr)
        self.t    = self.ax.set_title(self.fname)

    def addsamprate(self):
        try: self.t
        except AttributeError:
            self.plot()

        self.t    = self.ax.set_title(self.fname + " : %e Hz" % self.samprate)

    def show(self):
        mplt.show()

